package services

import (
	"database/sql"
	"fmt"
	"web2/pkg/models"
)

func CreateCategory(db *sql.DB, category *models.Category) (int64, error) {
	result, err := db.Exec(`
        INSERT INTO categories (name, parent_id, description, sort_order)
        VALUES (?, ?, ?, ?)
    `, category.Name, category.ParentID, category.Description, category.SortOrder)

	if err != nil {
		return 0, fmt.Errorf("创建分类失败: %v", err)
	}

	return result.LastInsertId()
}

func GetCategory(db *sql.DB, id int) (*models.Category, error) {
	var category models.Category
	err := db.QueryRow(`
        SELECT id, name, parent_id, description, sort_order
        FROM categories WHERE id = ?
    `, id).Scan(&category.ID, &category.Name, &category.ParentID,
		&category.Description, &category.SortOrder)

	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("分类不存在")
		}
		return nil, fmt.Errorf("查询分类失败: %v", err)
	}

	return &category, nil
}

func GetAllCategories(db *sql.DB) ([]models.Category, error) {
	rows, err := db.Query(`
        SELECT id, name, parent_id, description, sort_order
        FROM categories ORDER BY sort_order ASC
    `)
	if err != nil {
		return nil, fmt.Errorf("查询分类列表失败: %v", err)
	}
	defer rows.Close()

	var categories []models.Category
	for rows.Next() {
		var c models.Category
		if err := rows.Scan(&c.ID, &c.Name, &c.ParentID,
			&c.Description, &c.SortOrder); err != nil {
			return nil, fmt.Errorf("扫描分类数据失败: %v", err)
		}
		categories = append(categories, c)
	}

	return categories, nil
}

func DeleteCategory(db *sql.DB, id int) error {
	// 先检查是否有子分类
	var childCount int
	err := db.QueryRow(`
        SELECT COUNT(*) FROM categories WHERE parent_id = ?
    `, id).Scan(&childCount)

	if err != nil {
		return fmt.Errorf("检查子分类失败: %v", err)
	}

	if childCount > 0 {
		return fmt.Errorf("该分类下有子分类，不能删除")
	}

	// 执行删除
	_, err = db.Exec("DELETE FROM categories WHERE id = ?", id)
	if err != nil {
		return fmt.Errorf("删除分类失败: %v", err)
	}

	return nil
}
